package com.platform.comm.exceptions;


public class BizException extends RuntimeException {

    private static final long serialVersionUID = -1905740792987165967L;

    private final IErrorCode errorCode;
    private final String message;

    public BizException(String message) {
        super(message);
        this.message = message;
        this.errorCode = new DefaultErrorCode();
    }

    public static BizException of(String message){
        return new BizException(message);
    }

    public BizException(String message, Throwable e) {
        super(message, e);
        this.message = message;
        this.errorCode = new DefaultErrorCode();
    }

    public BizException(IErrorCode errorCode) {
        super();
        this.message = null;
        this.errorCode = errorCode;
    }

    public BizException(IErrorCode errorCode, String message) {
        super(message);
        this.message = message;
        this.errorCode = errorCode;
    }

    public BizException(IErrorCode errorCode, Throwable e) {
        super(e);
        this.message = e.getMessage();
        this.errorCode = errorCode;
    }

    public BizException(IErrorCode errorCode, String message, Throwable e) {
        super(message, e);
        this.message = message;
        this.errorCode = errorCode;
    }

    public BizException(BizException e) {
        super(e);
        this.message = e.getMessage();
        this.errorCode = e.errorCode;
    }

    // -----------------------------------------------------------------

    @Override
    public String getMessage() {
        if (message == null) {
            return this.errorCode == null ? this.errorCode.getErrorMessage() : null;
        } else {
            return message;
        }
    }

    @Override
    public String toString() {
        return String.format("[%s] %s", getClass().getSimpleName(), getMessage());
    }

    // -----------------------------------------------------------------

    public IErrorCode getErrorCode() {
        return errorCode;
    }

    // -----------------------------------------------------------------

    private static class DefaultErrorCode implements IErrorCode {

        @Override
        public Integer getErrorNo() {
            return -1;
        }

        @Override
        public String getErrorCode() {
            return "0xFFFF";
        }

        @Override
        public String getErrorMessage() {
            return buildErrorMessage("");
        }

        @Override
        public String buildErrorMessage(String message) {
            return String.format("[%s] %s", getErrorCode(), message == null ? getErrorMessage() : message);
        }

    }

}
